<template>
  <div class="file-upload-component">
    <el-upload
      ref="uploadRef"
      action="/api/user/upload"
      :headers="headers"
      :data="uploadData"
      name="file"
      :multiple="multiple"
      :accept="accept"
      :on-success="handleSuccess"
      :on-error="handleError"
      :on-progress="handleProgress"
      :on-change="handleChange"
      :before-upload="beforeUpload"
      :before-remove="beforeRemove"
      :list-type="listType"
      :auto-upload="autoUpload"
      :file-list="fileList"
      :disabled="disabled"
      :limit="limit"
      :on-exceed="handleExceed"
      :drag="drag"
      :show-file-list="showFileList"
      class="upload-container"
    >
      <el-button type="primary">
        <el-icon><Upload /></el-icon>
        选择文件
      </el-button>
      <template #tip>
        <div class="el-upload__tip">{{ tip }}</div>
      </template>
    </el-upload>

    <!-- 文件列表展示 -->
    <div v-if="showFileList && fileList.length > 0" class="file-list">
      <div
        v-for="file in fileList"
        :key="file.uid || (file as any).id"
        class="file-item"
        @click="handleFileClick(file)"
      >
        <div class="file-info">
          <div class="file-name">{{ file.name || (file as any).fileName }}</div>
          <div class="file-size">{{ formatFileSize(file.size || (file as any).fileSize) }}</div>
        </div>
        
        <el-button
          v-if="!disabled"
          type="danger"
          size="small"
          circle
          class="delete-btn"
          @click.stop="handleRemove(file)"
        >
          <el-icon><Delete /></el-icon>
        </el-button>
      </div>
    </div>

    <!-- 上传进度 -->
    <el-progress
      v-if="uploadProgress > 0 && uploadProgress < 100"
      :percentage="uploadProgress"
      :status="uploadStatus"
      class="upload-progress"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Upload, Delete } from '@element-plus/icons-vue'
import type { UploadUserFile, UploadProps, UploadRawFile, UploadFiles } from 'element-plus'
import { showError, showSuccess, showWarning } from '@/utils/message'

interface Props {
  uploadType?: string
  uploadSource?: string
  multiple?: boolean
  accept?: string
  listType?: 'text' | 'picture' | 'picture-card'
  autoUpload?: boolean
  modelValue?: UploadUserFile[]
  disabled?: boolean
  limit?: number
  drag?: boolean
  showFileList?: boolean
  tip?: string
  maxSize?: number
  allowedTypes?: string[]
}

const props = withDefaults(defineProps<Props>(), {
  uploadType: 'OTHER',
  uploadSource: 'WEB',
  multiple: false,
  accept: '*',
  listType: 'text',
  autoUpload: true,
  disabled: false,
  limit: 10,
  drag: false,
  showFileList: true,
  tip: '请选择要上传的文件（最大10MB）',
  maxSize: 10, // 10MB
  allowedTypes: () => []
})

const emit = defineEmits<{
  'update:modelValue': [files: UploadUserFile[]]
  'on-success': [response: any, file: any, fileList: UploadUserFile[]]
  'on-error': [error: Error, file: any, fileList: UploadUserFile[]]
  'on-progress': [event: any, file: any, fileList: UploadUserFile[]]
  'on-change': [file: any, fileList: UploadUserFile[]]
  'on-remove': [file: any, fileList: UploadUserFile[]]
  'on-file-click': [file: any]
}>()

const uploadRef = ref()
const uploadProgress = ref(0)
const uploadStatus = ref<'success' | 'exception' | ''>('')

const fileList = computed({
  get: () => props.modelValue || [],
  set: (value) => emit('update:modelValue', value)
})

const headers = computed(() => {
  const token = localStorage.getItem('token')
  return {
    Authorization: token ? `Bearer ${token}` : ''
  }
})

const uploadData = computed(() => ({
  uploadType: props.uploadType,
  uploadSource: props.uploadSource
}))

const beforeUpload = (rawFile: UploadRawFile) => {
  if (props.maxSize && rawFile.size / 1024 / 1024 > props.maxSize) {
    showError(`文件大小不能超过 ${props.maxSize}MB`)
    return false
  }

  if (props.allowedTypes.length > 0) {
    const fileName = rawFile.name
    const fileExt = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase()
    const isTypeAllowed = props.allowedTypes.some(type => fileExt === type)
    
    if (!isTypeAllowed) {
      showError(`只允许上传 ${props.allowedTypes.join(', ')} 格式的文件`)
      return false
    }
  }

  uploadProgress.value = 0
  uploadStatus.value = ''
  return true
}

const beforeRemove = (file: any, uploadFiles: UploadUserFile[]) => {
  return ElMessageBox.confirm('确定要删除这个文件吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => true).catch(() => false)
}

const handleFileClick = (file: any) => {
  emit('on-file-click', file)
  if (file.url) {
    window.open(file.url)
  }
}

const handleRemove = (file: any) => {
  return ElMessageBox.confirm('确定要删除这个文件吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 从文件列表中移除指定文件
    const currentFiles = Array.isArray(props.modelValue) ? [...props.modelValue] : []
    const fileIndex = currentFiles.findIndex(f => 
      (f.uid && f.uid === file.uid) || 
      ((f as any).id && (f as any).id === (file as any).id) ||
      (f.name === file.name && f.size === file.size)
    )
    
    if (fileIndex > -1) {
      currentFiles.splice(fileIndex, 1)
      emit('update:modelValue', currentFiles)
      emit('on-remove', file, currentFiles)
      showSuccess('文件删除成功')
    }
  }).catch(() => {
    // 取消删除
  })
}

const handleSuccess = (response: any, file: any, uploadFiles: UploadUserFile[]) => {
  uploadProgress.value = 100
  uploadStatus.value = 'success'

  if (response && response.data) {
    file.url = response.data.fileUrl
    ;(file as any).fileName = response.data.fileName
    ;(file as any).fileSize = response.data.fileSize
    ;(file as any).id = response.data.id
  }

  emit('update:modelValue', uploadFiles)
  emit('on-success', response, file, uploadFiles)
  showSuccess('上传成功')

  setTimeout(() => {
    uploadProgress.value = 0
    uploadStatus.value = ''
  }, 2000)
}

const handleError = (error: Error, file: any, uploadFiles: UploadUserFile[]) => {
  uploadProgress.value = 100
  uploadStatus.value = 'exception'
  
  // 解析错误信息
  let errorMessage = '上传失败'
  if (error.message && error.message.includes('文件大小不能超过')) {
    errorMessage = '文件大小超过限制，请选择小于10MB的文件'
  } else if (error.message && error.message.includes('不支持的文件类型')) {
    errorMessage = '不支持的文件类型，请选择正确的文件格式'
  }
  
  emit('on-error', error, file, uploadFiles)
  showError(errorMessage)

  setTimeout(() => {
    uploadProgress.value = 0
    uploadStatus.value = ''
  }, 2000)
}

const handleProgress = (event: any, file: any, uploadFiles: UploadUserFile[]) => {
  uploadProgress.value = Math.round(event.percent || 0)
  emit('on-progress', event, file, uploadFiles)
}

const handleChange = (file: any, uploadFiles: UploadUserFile[]) => {
  // 确保uploadFiles是数组，避免undefined错误
  const safeUploadFiles = Array.isArray(uploadFiles) ? uploadFiles : []
  
  // 检查文件状态，如果是删除操作，不重复处理
  if (file.status === 'removed') {
    return
  }
  
  emit('update:modelValue', safeUploadFiles)
  emit('on-change', file, safeUploadFiles)
}

const handleExceed = (files: any) => {
  showWarning(`最多只能上传 ${props.limit} 个文件`)
}

const formatFileSize = (size: number) => {
  if (!size) return '0 B'
  
  const units = ['B', 'KB', 'MB', 'GB', 'TB']
  let unitIndex = 0
  let fileSize = size
  
  while (fileSize >= 1024 && unitIndex < units.length - 1) {
    fileSize /= 1024
    unitIndex++
  }
  
  return `${fileSize.toFixed(2)} ${units[unitIndex]}`
}

const clearFiles = () => {
  uploadRef.value?.clearFiles()
}

const submit = () => {
  uploadRef.value?.submit()
}

const abort = () => {
  uploadRef.value?.abort()
}

defineExpose({
  clearFiles,
  submit,
  abort
})
</script>

<style lang="scss" scoped>
.file-upload-component {
  .upload-container {
    width: 100%;
  }

  .upload-progress {
    margin-top: 10px;
  }

  .file-list {
    margin-top: 16px;
  }

  .file-item {
    display: flex;
    align-items: center;
    padding: 8px 12px;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    margin-bottom: 8px;
    cursor: pointer;
    transition: all 0.3s;
    position: relative;

    &:hover {
      border-color: #409eff;
      background-color: #f5f7fa;
    }

    .file-info {
      flex: 1;
      min-width: 0;

      .file-name {
        font-size: 14px;
        color: #303133;
        margin-bottom: 4px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .file-size {
        font-size: 12px;
        color: #909399;
      }
    }

    .delete-btn {
      margin-left: 8px;
      opacity: 0;
      transition: opacity 0.3s;
    }

    &:hover .delete-btn {
      opacity: 1;
    }
  }
}
</style> 